#!/usr/bin/env bash
#
# narsil-docker.sh - Install docker service
# Seaton Jiang <hi@seatonjiang.com>
#
# The latest version of Narsil can be found at:
# https://github.com/seatonjiang/narsil
#
# Copyright (C) 2023 Seaton Jiang
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.

function narsil_docker()
{
    msg_notic '\n%s\n\n' "Docker-ce is being installed, please wait..."

    narsil_docker_ce='http://mirrors.tencent.com/docker-ce/linux/centos/docker-ce.repo'
    narsil_docker_mirrors='mirrors.tencent.com'
    narsil_docker_hub='https://hub-mirror.c.163.com'

    if [[ ${METADATA} == "Y" ]]; then
        if [ -n "$(wget -qO- -t1 -T2 metadata.tencentyun.com)" ]; then
            docker_ce='http://mirrors.tencentyun.com/docker-ce/linux/centos/docker-ce.repo'
            docker_mirrors='mirrors.tencentyun.com'
            docker_hub='https://mirror.ccs.tencentyun.com'
        fi
    fi

    if [ "${narsil_docker_ce}" != "${DOCKER_CE_REPO}" ]; then
        docker_ce=${DOCKER_CE_REPO}
    fi

    if [ "${narsil_docker_mirrors}" != "${DOCKER_CE_MIRROR}" ]; then
        docker_mirrors=${DOCKER_CE_MIRROR}
    fi

    if [ "${narsil_docker_hub}" != "${DOCKER_HUB_MIRRORS}" ]; then
        docker_hub=${DOCKER_HUB_MIRRORS}
    fi

    # Uninstall Docker Engine
    dnf remove -y docker* containerd.io podman* runc >/dev/null 2>&1

    # Install Dependencies
    dnf config-manager --add-repo "${docker_ce}"
    sed -i "s|download.docker.com|${docker_mirrors}/docker-ce|g" /etc/yum.repos.d/docker-ce.repo

    # Install Docker
    dnf install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

    mkdir -p /etc/docker
    echo "{\"registry-mirrors\":[\"${docker_hub}\"]}" > /etc/docker/daemon.json

    systemctl restart docker.service
    systemctl enable docker.service

    if [[ ${VERIFY} == "Y" ]]; then
        msg_notic '\n%s\n' "• Docker version"
        docker version
        msg_notic '\n%s\n' "• Docker compose version"
        docker compose version
    fi

    printf '\n%s%s\n%s%s\n\n' "$(tput setaf 6)" \
    "Done, please use \`docker run hello-world\` to test." \
    "The log of this execution can be found at ${LOGFILE}" \
    "$(tput sgr0)" >&3
}
